//
//  NetworkingManager.swift
//  SwiftBaseProject
//
//  Created by 苏州巨细 on 2018/5/22.
//  Copyright © 2018年 苏州巨细. All rights reserved.
//

import Foundation
import Moya
import SwiftyJSON
import enum Result.Result
import Reachability


/// 成功回调
typealias SuccessClosure = (_ result: JSON) -> Void

/// 失败回调
typealias FailClosure = (_ errorCode: Int,_ errorMsg: String?) -> Void
    

class NetworkingManager {
    
    /// 使用单例
    static let shared = NetworkingManager()
    
    /// 加载提示框插件（本想在此边在协议里面添加一个shouHUD参数，但需要改动pod，不方便，所以现在选择将显示HUD的条件用path来判断）
    /// 现在添加一个扩展参数，每个类里面去实现（逻辑判断在里面），但在这边需要多加一步类型转换判断
    let networkActivityPlugin = NetworkActivityPlugin { type,target  in
        
        //消息列表单独请求未读消息不需要HUD
        if target is LoginModuleHttp {
            let loginTarget = target as! LoginModuleHttp
            if loginTarget.showHUD == false {
                return
            }
        }
        
        
        switch type {
        case .began:
            HUDUtil.showMessage("", withDelay: 20)
        case .ended:
            HUDUtil.hiddenHUD()
        }
        
    }
    
    /// 打印请求信息插件
    let loggerPlugin = RequestLoggerPlugin.init()
    
    private init(){
        
        //开启网络监听
        let reachability = Reachability()!
        
        do {
            try reachability.startNotifier()
        } catch {
            print("Unable to start notifier")
        }
    }
    
    func requestData<T:TargetType>(target:T,successClosure:@escaping SuccessClosure,failClosure: @escaping FailClosure) {
        let requestProvider = MoyaProvider<T>(requestClosure:requestTimeoutClosure(target: target),plugins:[networkActivityPlugin,loggerPlugin])
        
        let reachability = Reachability()!
        
        if reachability.connection == .none {
            
            HUDUtil.showSuccess("当前没有网络连接")
            failClosure(1005,"当前没有网络连接")
            return
        }
        
        let _=requestProvider.request(target) { (result) -> () in
            
            switch result{
            case let .success(response):
                if response.statusCode == 200 {
                    let json = JSON(response.data)
                    if json["code"].doubleValue == 0 {
                        successClosure(json["data"])
                    }else{
                        HUDUtil.showSuccess(json["msg"].stringValue)
                        //错误信息通知外部，让外部去处理
                        failClosure(json["code"].intValue,json["msg"].stringValue)
                    }
                }else{
                    //接口问题，暂未处理
                    failClosure(0,"错误了")
                }
                
            case let .failure(error):
                failClosure(0,error.errorDescription)
            }
        }
        
    }
    
    /// 设置请求超时闭包
    ///
    /// - Parameter target: 请求target
    /// - Returns: 请求闭包
    private func requestTimeoutClosure<T:TargetType>(target:T) -> MoyaProvider<T>.RequestClosure{
        let requestTimeoutClosure = { (endpoint:Endpoint, done: @escaping MoyaProvider<T>.RequestResultClosure) in
            do{
                var request = try endpoint.urlRequest()
                request.timeoutInterval = 20 //设置请求超时时间
                done(.success(request))
            }catch{
                return
            }
        }
        return requestTimeoutClosure
    }
    
}



